﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;


public class UtilsList
{
    /// <summary>
    /// get local file length 
    /// </summary>
    /// <param name="filename">local file name</param>
    /// <returns>file length</returns>
    public static long GetLocalFileLength(string filename)
    {
        long length=0;
        try
        {
            FileInfo finfo = new FileInfo(filename);
            length = finfo.Length;
        }
        catch
        {
            length = -1;
        }
        return length;
    }

    /// <summary>
    /// get remote file length
    /// </summary>
    /// <param name="fileurl">file url</param>
    /// <returns>file length of long type</returns>
    public static long GetRemoteFileLength(string fileurl)
    {
        long length = 0;
        HttpWebResponse resp = null;
        StreamReader sr = null;
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(fileurl);
            req.UserAgent = "patentbutcherclient";
            resp = (HttpWebResponse)req.GetResponse();
            length = resp.ContentLength;
            if (length == -1)
            {
                sr = new StreamReader(resp.GetResponseStream());
                length = sr.ReadToEnd().Length;
            }
        }
        catch
        {
            length = -1;
        }
        finally
        {
            if (sr != null)
                sr.Close();
            if (resp != null)
                resp.Close();
        }
        return length;
    }

    public static void DownloadFile(string savepath, string url)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.UserAgent = "patentbutcherclient";
        WebResponse resp = req.GetResponse();
        Stream stream = resp.GetResponseStream();

        FileStream fs = new FileStream(savepath, FileMode.Create);

        byte[] nbytes = new byte[512];
        int nReadSize = 0;
        nReadSize = stream.Read(nbytes, 0, 512);
        while (nReadSize > 0)
        {
            fs.Write(nbytes, 0, nReadSize);
            nReadSize = stream.Read(nbytes, 0, 512);
        }


        fs.Close();
        stream.Close();
        resp.Close();
        return;
    }
  
    public static string GetHtmlPage(string url)
    {
        string htmlSource = "";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.UserAgent = "patentbutcherclient";
        WebResponse resp = req.GetResponse();
        Stream stream = resp.GetResponseStream();
        StreamReader sr = new StreamReader(stream);
        htmlSource = sr.ReadToEnd();
        sr.Close();
        stream.Close();
        resp.Close();

        return htmlSource;
    }
    public static string GetHtmlPage(string url, string pageencoding)
    {
        string htmlSource = "";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        WebResponse resp = req.GetResponse();
        Stream stream = resp.GetResponseStream();
        StreamReader sr = new StreamReader(stream, Encoding.GetEncoding(pageencoding));
        htmlSource = sr.ReadToEnd();
        sr.Close();
        stream.Close();
        resp.Close();

        return htmlSource;
    }

    public static string GetHtmlPage(string url, CookieContainer cc)
    {
        string htmlSource = "";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.CookieContainer = cc;
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        resp.Cookies = cc.GetCookies(req.RequestUri);
        Stream stream = resp.GetResponseStream();
        StreamReader sr = new StreamReader(stream);
        htmlSource = sr.ReadToEnd();
        sr.Close();
        stream.Close();
        resp.Close();

        return htmlSource;
    }



    /// <summary>
    /// 通过post方式获得网页
    /// </summary>
    /// <param name="posturl">接受数据的网页</param>
    /// <param name="postdata">提交的数据</param>
    //statenow=1&year=%E5%85%A8%E9%83%A8&drtype=&apptype=&acceptid=&drugname=&currentPageNumber=1&pageMaxNumber=20&max=395&pageroffset=0&pagenum=
    public static string PostHtmlPage(string posturl, string postdata)
    {
        string htmlsrc = "";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(postdata);
        try
        {
            // Prepare web request...
            HttpWebRequest myRequest =
              (HttpWebRequest)WebRequest.Create(posturl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream;

            // Send the data.
            using (newStream = myRequest.GetRequestStream())
            {
                newStream.Write(data, 0, data.Length);
                newStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)myRequest.GetResponse();
            Stream stream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            htmlsrc = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            resp.Close();
        }
        catch (WebException ex)
        {
            return PostHtmlPage(posturl, postdata);
        }
        return htmlsrc;
    }

    public static string PostHtmlPage(string posturl, string postdata, string pageencoding)
    {
        string htmlsrc = "";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(postdata);

        // Prepare web request...
        HttpWebRequest myRequest =
          (HttpWebRequest)WebRequest.Create(posturl);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.ContentLength = data.Length;
        Stream newStream;

        // Send the data.
        using (newStream = myRequest.GetRequestStream())
        {
            newStream.Write(data, 0, data.Length);
            newStream.Close();
        }

        HttpWebResponse resp = (HttpWebResponse)myRequest.GetResponse();
        Stream stream = resp.GetResponseStream();
        StreamReader sr = new StreamReader(stream, Encoding.GetEncoding(pageencoding));
        htmlsrc = sr.ReadToEnd();
        sr.Close();
        stream.Close();
        resp.Close();

        return htmlsrc;
    }
    /// <summary>
    /// 删除最后下载的一个文件，因为他可能没有下载完整
    /// </summary>
    /// <param name="path"></param>
    public static void DeleteLatestFile(string path)
    {
        List<string> dir = new List<string>();
        foreach (string fi in Directory.GetFiles(path))
        {
            dir.Add(fi);
        }
        if (dir.Count < 1)
            return;
        //对得到的文件名称进行排序
        dir.Sort(UtilsList.CompareDinosByLength);

        File.Delete(dir[dir.Count - 1]);
    }
    public static Dictionary<string, string> ParseParams(string urlparams)
    {
        Dictionary<string, string> namevalues = new Dictionary<string, string>();
        string[] nvs = urlparams.Split(new char[] { '&' });
        foreach (string s in nvs)
        {
            string[] nv = s.Split(new char[] { '=' });
            namevalues.Add(nv[0], nv[1]);
        }
        return namevalues;
    }


    public static int CompareDinosByLength(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
            // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the 
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }
    }

    public static string ArraytoString(string[] strs)
    {
        string str = "";
        for (int i = 0; i < strs.Length; i++)
        {
            str += strs[i] + "\t";
        }

        return str;
    }

    public static string ListtoString<T>(List<T> list)
    {
        string str = "";
        for (int i = 0; i < list.Count; i++)
        {
            str += list[i].ToString() + "\r\n";
        }

        return str;
    }
    public static string DicttoString<K, V>(Dictionary<K, V> dict)
    {
        string str = "";
        foreach (K k in dict.Keys)
        {
            str += k.ToString() + ": " + dict[k].ToString() + "\r\n";
        }

        return str;
    }

}


   